package cn.autumnorange.app.money.provider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

/** Created by QinHe on 2018-07-24. */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "entityManagerFactorySecondary",
    transactionManagerRef = "transactionManagerSecondary",
    basePackages = {"cn.autumnorange.app.money.provider.repository"}) // 设置Repository所在位置
public class SecondaryConfig {

  @Resource(name = "secondaryDataSource")
  private DataSource secondaryDruidDataSource;

  @Autowired private JpaProperties jpaProperties;

  @Primary
  @Bean(name = "entityManagerFactorySecondary")
  public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
      EntityManagerFactoryBuilder builder) {
    return builder
        .dataSource(secondaryDruidDataSource)
        .properties(getVendorProperties(secondaryDruidDataSource))
        .packages("cn.autumnorange.app.money.provider.entity") // 设置实体类所在位置
        .persistenceUnit("secondaryPersistenceUnit")
        .build();
  }

  @Primary
  @Bean(name = "entityManagerSecondary")
  public EntityManager entityManagerSecondary(EntityManagerFactoryBuilder builder) {
    return entityManagerFactorySecondary(builder).getObject().createEntityManager();
  }

  private Map<String, Object> getVendorProperties(DataSource dataSource) {
    HibernateSettings hibernateSettings = new HibernateSettings();
    return jpaProperties.getHibernateProperties(hibernateSettings);

    //        return jpaProperties.getHibernateProperties(dataSource);
  }

  @Primary
  @Bean(name = "transactionManagerSecondary")
  public PlatformTransactionManager transactionManagerSecondary(
      EntityManagerFactoryBuilder builder) {
    return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
  }
}
